package com.titar.robot.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.titar.robot.R;
import com.titar.robot.RobotApp;
import com.titar.robot.ui.dialog.ComfirmDialog;
import com.titar.robot.ui.dialog.LoadingDialog;
import com.titar.robot.ui.dialog.TipDialog;
import com.titar.robot.ui.welcom.WelcomeActivity;
import com.titar.robot.utils.TipBarUtil;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

public abstract class BaseActivity<T extends BasePresenter> extends PermissionsActivity implements BaseView {

    String TAG = this.getClass().getSimpleName();

    public T mPresenter;

    protected ViewGroup rootView;
    protected TipBarUtil mTipBarUtil;


    private BroadcastReceiver mNetWorkStateReceiver = new NetworkStateRecevier();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.activity_base, null, false);
        mTipBarUtil = new TipBarUtil(rootView.findViewById(R.id.tip_bar));
        super.setContentView(rootView);
        setContentView(getContentViewId());


        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(mNetWorkStateReceiver, intentFilter);

        //初始化view
        onInitWidget(savedInstanceState);

        //设置view的事件监听
        onInitListener();

    }

    /* view的初始化或回显操作*/
    protected abstract void onInitWidget(Bundle savedInstanceState);

    /* view的事件监听配置*/
    protected abstract void onInitListener();


    @Override
    protected void onResume() {
        super.onResume();
        if (!RobotApp.getIsLife()) {
            //程序已经被回收
            RobotApp.isLife = true;
            Intent intent = new Intent(BaseActivity.this, WelcomeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);//销毁之前所有activity
            BaseActivity.this.startActivity(intent);
            return;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        unregisterReceiver(mNetWorkStateReceiver);
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        //super.setContentView(layoutResID);
        setContentView(View.inflate(this, layoutResID, null));
    }

    @Override
    public void setContentView(View view) {
        rootView.addView(view, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
    }

    public abstract int getContentViewId();


    //////////////////////////////////////////////////////////////////
    ////////////////////////BaseView--impl///////////////////////////////
    /////////////////////////////////////////////////////////////////
    @Override
    public void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(BaseActivity.this);
            loadingDialog.setCancelable(false);
            loadingDialog.setCanceledOnTouchOutside(false);
        }
        if (!loadingDialog.isShowing())
            loadingDialog.show();
    }

    private LoadingDialog loadingDialog;

    @Override
    public void showLoadingDialog(String msg) {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(BaseActivity.this);
            loadingDialog.setCancelable(false);
            loadingDialog.setCanceledOnTouchOutside(false);
        }
        if (!loadingDialog.isShowing())
            loadingDialog.show(msg);
    }

    @Override
    public void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void showErrorDialog() {
        TipDialog.show(BaseActivity.this, "Error", null);
    }


    @Override
    public void showErrorDialog(String content, boolean cancelable) {
        TipDialog.show(BaseActivity.this, content, null);
    }


    protected void showDialog(String title, String msg, View.OnClickListener positiveButtonClickListener, View.OnClickListener negativeButtonClickListener) {
        ComfirmDialog.show(BaseActivity.this, title, msg, positiveButtonClickListener, negativeButtonClickListener);
    }
    //////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////


    //////////////////////////////////////////////////////////////////////////
    ////////////////////////////=====页面跳转======//////////////////////////
    /////////////////////////////////////////////////////////////////////////
    protected void jump2Activity(Class clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    protected void jump2ActivityForResult(Class clazz, int requestCode) {
        Intent intent = new Intent(this, clazz);
        startActivityForResult(intent, requestCode);
    }

    protected void jump2ActivityAndFinish(Class clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
        finish();
    }

    ////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////


    //////////////////////////////////////////////////////////////////////////
    ////////////////////////////=====repleaceFragment======///////////////////
    //////////////////////////////////////////////////////////////////////////
    protected void repleaceFragment(Fragment fragment, @IdRes int frameLayoutId) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(frameLayoutId, fragment, "")
                .commit();
    }
    ////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////


    //////////////////////////////////////////////////////////////////////////
    ////////////////////////////=====onBackPressed======///////////////////
    //////////////////////////////////////////////////////////////////////////
    @Override
    public void onBackPressed() {

    }

    ////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////


    //////////////////////////////////////////////////////////////////////////
    ////////////////////////////=====网络状态监听======///////////////////
    //////////////////////////////////////////////////////////////////////////
    public class NetworkStateRecevier extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.w(TAG, intent.getAction());
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
            if (activeNetwork != null) {    // connected to the internet
                if (activeNetwork.isConnected()) {
                    Log.e(TAG, "当前WiFi连接可用");

                } else {
                    Log.e(TAG, "当前移动网络连接可用");

                }
                //发送有网通知
                mTipBarUtil.close();
            } else {
                Log.e(TAG, "当前没有网络连接，请确保你已经打开网络");
                mTipBarUtil.tipError(getString(R.string.network_anomaly));

            }
        }
    }

    ////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////

    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            PackageInfo info;
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
}
